package com.alibaba.cirtus.ots.application.app.ability.facade.v2serviceimpl;

import com.alibaba.cz.base.tool.log.Log;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.lattice2.epoch.sdk.model.Result;
import com.epoch.app.otsapplicationappsdk.transferdetaillist.dto.AsyncRequest;
import com.epoch.app.otsapplicationappsdk.transferdetaillist.dto.RenderRequest;
import com.epoch.app.otsapplicationappsdk.transferdetaillist.service.TransferDetailListService;
import com.epoch.app.crunifiedinventory.api.allocateapplyorderdropdownselection.service.AllocateApplyOrderDropDownSelectionService;
import com.epoch.app.crunifiedinventory.api.allocateapplyorderread.service.AllocateApplyOrderReadService;
import com.epoch.app.crunifiedinventory.dto.response.AllocateApplyOrderListDTO;
import com.epoch.app.crunifiedinventory.model.dto.AllocateApplyOrderQueryRequest;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;


@Service
public class TransferDetailListV2ServiceImpl implements TransferDetailListService {

    private static Log log = Log.getLogger(TransferDetailListV2ServiceImpl.class);

    @Resource
    AllocateApplyOrderReadService allocateApplyOrderReadService;

    @Resource
    AllocateApplyOrderDropDownSelectionService allocateApplyOrderDropDownSelectionService;

    @Override
    public Object render(RenderRequest renderRequest) {
        JSONObject result = new JSONObject();
        JSONObject data = new JSONObject();
        try {
            log.info("调拨预报单列表渲染 请求参数 {} ", JSON.toJSONString(renderRequest));
            JSONObject request = (JSONObject)JSONObject.toJSON(renderRequest.getRequest());
            if (request.get("page") == null) {
                request.put("page",1);
            }
            if (request.get("size") == null) {
                request.put("size",10);
            }
            Result<List<AllocateApplyOrderListDTO>> callApiResult = renderData(request);
            log.info("调拨预报单列表渲染 预报单接口出参 {} ", JSON.toJSONString(callApiResult));

            //单据类型
            Object  allocateApplyOrderDropDownSelection = allocateApplyOrderDropDownSelectionService.queryDocumentType();
            log.info("调拨预报单创建渲染 调拨类型 {} ",JSONObject.toJSONString(allocateApplyOrderDropDownSelection));
            JSONObject allocateApplyOrderDropDownSelectionJson = (JSONObject)JSONObject.toJSON(allocateApplyOrderDropDownSelection);
            data.put("allocationType",allocateApplyOrderDropDownSelectionJson.getJSONArray("result"));

            if (request.get("page") == null || request.getInteger("page") <= 1) {
                data.put("reload",true);
            } else {
                data.put("reload",false);
            }
            data.put("list",callApiResult.getResult());
            data.put("page",request.getInteger("page"));
            data.put("size",request.getInteger("size"));
            data.put("status","99");
            data.put("totalPage",Math.ceil((double) callApiResult.getTotal()/(double)request.getInteger("size")));
            result.put("success",true);
            result.put("result",data);
        } catch (Exception e) {
            log.info("调拨预报单列表渲染异常 {}", e.getMessage());
            result.put("success",false);
            result.put("message","调拨预报单列表渲染异常");
        }
        log.info("调拨预报单列表渲染 出参 {} ", JSON.toJSONString(result));
        return result;
    }

    @Override
    public Object async(AsyncRequest asyncRequest) {
        JSONObject result = new JSONObject();
        try {
            log.info("调拨预报单列表异步渲染 请求参数 {} ", JSON.toJSONString(asyncRequest));
            JSONObject request = (JSONObject)JSONObject.toJSON(asyncRequest.getRequest());

            JSONObject updateFields = new JSONObject();
            if (request != null) {
                if (request.get("fields") != null) {
                    JSONObject fieldsJson = request.getJSONObject("fields");
                    updateFields = fieldsJson.getJSONObject("updateFields");
                }
            }
            if (updateFields.get("page") == null) {
                updateFields.put("page",1);
            }
            if (updateFields.get("size") == null) {
                updateFields.put("size",10);
            }
            Result<List<AllocateApplyOrderListDTO>> callApiResult = renderData(updateFields);
            log.info("调拨预报单列表异步渲染 预报单接口出参 {} ", JSON.toJSONString(callApiResult));
            JSONObject data = new JSONObject();
            if (updateFields.get("page") == null || updateFields.getInteger("page") <= 1) {
                data.put("reload",true);
            } else {
                data.put("reload",false);
            }

            //单据类型
            Object  allocateApplyOrderDropDownSelection = allocateApplyOrderDropDownSelectionService.queryDocumentType();
            log.info("调拨预报单创建渲染 调拨类型 {} ",JSONObject.toJSONString(allocateApplyOrderDropDownSelection));
            JSONObject allocateApplyOrderDropDownSelectionJson = (JSONObject)JSONObject.toJSON(allocateApplyOrderDropDownSelection);
            data.put("allocationType",allocateApplyOrderDropDownSelectionJson.getJSONArray("result"));

            data.put("list",callApiResult.getResult());
            data.put("page",updateFields.getInteger("page"));
            data.put("size",updateFields.getInteger("size"));
            data.put("status",updateFields.getString("status"));
            data.put("scItemCode",updateFields.getString("scItemCode"));
            data.put("selected",updateFields.get("selected"));
            data.put("totalPage",Math.ceil((double) callApiResult.getTotal()/(double)updateFields.getInteger("size")));
            result.put("success",true);
            result.put("result",data);
        } catch (Exception e) {
            e.printStackTrace();
            log.info("调拨预报单列表异步渲染异常 {}", e.getMessage());
            result.put("success",false);
            result.put("message","调拨预报单列表异步渲染异常");
        }
        log.info("调拨预报单列表异步 出参 {} ", JSON.toJSONString(result));
        return result;
    }

    public Result renderData(JSONObject request) {
        if (request == null) {
            return new Result();
        }
        AllocateApplyOrderQueryRequest allocateApplyOrderQueryRequest = new AllocateApplyOrderQueryRequest();
        Integer page = request.getInteger("page");
        Integer size = request.getInteger("size");

        Integer start=(page-1)*size;
        allocateApplyOrderQueryRequest.setStart(start);
        allocateApplyOrderQueryRequest.setLimit(size);
        if (request.get("status") != null) {
//            allocateApplyOrderQueryRequest.setStatus(Collections.singletonList(Integer.valueOf(request.getString("status"))));
            allocateApplyOrderQueryRequest.setLineStatus(Collections.singletonList(Integer.valueOf(request.getString("status"))));
        } else {
//            allocateApplyOrderQueryRequest.setStatus(Collections.singletonList(99));
            allocateApplyOrderQueryRequest.setLineStatus(Collections.singletonList(99));
        }
        if (request.get("code") != null && !"".equals(request.getString("code"))) {
            allocateApplyOrderQueryRequest.setCode(request.getString("code"));
        }

        if (request.get("startTime") != null && !"".equals(request.get("startTime"))) {
            allocateApplyOrderQueryRequest.setGmtCreateStart(request.getDate("startTime"));
        }
        if (request.get("endTime") != null && !"".equals(request.get("endTime"))) {
            allocateApplyOrderQueryRequest.setGmtCreateEnd(request.getDate("endTime"));
        }
        if (request.get("tagList") != null) {
            JSONArray tagListJson = request.getJSONArray("tagList");
            if (CollectionUtils.isNotEmpty(tagListJson)) {
                List<Integer> tagList = new ArrayList<>();
                for (Object obj : tagListJson) {
                    tagList.add(Integer.valueOf(obj.toString()));
                }
                allocateApplyOrderQueryRequest.setType(tagList);
            }
        }
        if (StringUtils.isNotBlank(request.getString("scItemCode"))) {
            allocateApplyOrderQueryRequest.setTitle(request.getString("scItemCode"));
        }

        Result<List<AllocateApplyOrderListDTO>> callApiResult = allocateApplyOrderReadService.queryAllocateApplyOrderList(allocateApplyOrderQueryRequest);

        return callApiResult;
    }

}
